// util
const mod = (a, b) => {
  let i = 0,
    rest = b
  while (a > 0) {
    a = a - b
    a > 0 ? i++ : rest = Math.ceil(a + b) // 余数
  }
  return [i + 1, rest]
}


// 按周分组
const processFormatForLesson = (timeTable) => {
  const weeks = {}
  let i = 0
  for (i; i < 20; i++) {
    weeks[i + 1] = {
      id: i + 1,
      lessons: []
    }
  }
  timeTable.forEach(lesson => {
    lesson.week_list.forEach(w => {
      weeks[w].lessons.push(lesson)
    })
  })
  console.log(weeks)
  return weeks
}

// 当前学期
const getTerm = () => {
  const laterTerm = [3, 4, 5, 6, 7] // 下学期
  const currentTime = new Date()
  const month = currentTime.getMonth() + 1 // 月份
  const day = currentTime.getDay()

  return (laterTerm.find(i => i === month) ||
      (month === 2 && day > 15) ||
      (month === 8 && day < 15)) ?
    2 : 1
}

// 计算当前周
const getCurrentWeek = () => {
  // 2020年开学日期 定期维护...
  const openDate = new Date("2020-09-07")
  const nowDate = new Date()
  const duringDays = (nowDate - openDate) / 1000 / 60 / 60 / 24

  return mod(duringDays, 7)
}

const getCurrentDates = (currentWeek) => {
  let currentDates = []
  const openDate = new Date("2020-09-07")
  const openDayOfWeek = openDate.getDay()
  const openDayOfMonth = openDate.getDate()

  //计算date
  for (let i = 0; i < 7; i++) {
    let currentDate = new Date(openDate)
    let currentDayOfWeek = i
    currentDate.setDate(openDayOfMonth + 7 * (currentWeek - 1) - openDayOfWeek + 1 + currentDayOfWeek)
    currentDates[i] = currentDate.getDate()
  }
  //计算month
  let firstDayOfWeek = new Date(openDate)
  firstDayOfWeek.setDate(openDayOfMonth + 7 * (currentWeek - 1) - openDayOfWeek + 1)

  return [currentDates, firstDayOfWeek.getMonth() + 1]
}

// 十六进制转rgb   复制粘贴
const hex2rgb = (arr) => {
  arr = arr.substr(1);
  var str;
  var result;
  var a = [];
  for (var i = 0; i < 3; i++) {
    str = arr.substr(i * 2, 2);
    a[i] = parseInt(str, 16);
  }
  result = "rgba(" + a[0] + ", " + a[1] + ", " + a[2] + ")";
  return result;
}

// 为每个课程添加颜色
const processColorForLessons = (colors, timetable) => {
  let i = 0
  const map = {}
  timetable.forEach(lesson => { // lesson: { id, name, room, teacher }
    !map[lesson.id] && (map[lesson.id] = colors[i++])
    lesson.color = hex2rgb(map[lesson.id])
  })

  return timetable
}

const throttle = (fn, delay, atleast) => {
  var timer = null;
  var previous = null;

  return function () {
    var now = +new Date();
    if (!previous) previous = now;
    if (now - previous > atleast) {
      fn();
      // 重置上一次开始时间为本次结束时间
      previous = now;
    } else {
      clearTimeout(timer);
      timer = setTimeout(function () {
        fn();
      }, delay);
    }
  }
};




/**
 * 处理原始课表数据
 */

const formatClassTable = (timetable) => {
  return _minData(timetable)
}

const _minData = (origin) => {
  let min = []
  let count = 0
  const map = new Map()
  origin.kbList.forEach((classes, index) => {
    let obj = {}
    let zcdModify = _modifyWeek(classes.zcd)
    let jcsModify = _modifyTime(classes.jcs)
    // obj.zcd = classes.zcd
    // obj.xqj = parseInt(classes.xqj)
    // obj.jcs = classes.jcs
    // obj.kcmc = classes.kcmc

    obj.week_list = zcdModify
    obj.start = jcsModify[0]
    obj.step = jcsModify.length
    obj.name = classes.kcmc
    obj.teacher = classes.xm
    obj.room = classes.cdmc
    obj.day = classes.xqj
    if (map[obj.name]) {
      obj.id = map[obj.name]
    } else {
      obj.id = count++
      map[obj.name] = obj.id
    }
    min.push(obj)
  })
  return min
}

// 处理课程时间
function _modifyTime(timeStr) {
  let result = []
  let arr = timeStr.split('-')
  let start = parseInt(arr[0])
  let end = parseInt(arr[arr.length - 1])
  for (let i = start; i <= end; i++) {
    result.push(i)
  }
  return result
}

// 处理周次
function _modifyWeek(weekStr) {
  // weekStr: "1-7周(单),9周"
  let arr = weekStr.split(',')
  let result = []
  arr.forEach((item) => {
    /** 
     * 获取起始和结束周次的数组，start为startAndEnd[0],end为startAndEnd的最后一项
     * 如果直接取第二项，可能会越界，如：9周,数组就是有一项
     **/
    let startAndEnd = item.split('-')
    let start = parseInt(startAndEnd[0])
    let end = parseInt(startAndEnd[startAndEnd.length - 1])
    let strArr = item.split('')
    // 判断是否有单双周
    if (strArr.includes('单') || strArr.includes('双')) {
      for (let i = start; i <= end; i = i + 2) {
        result.push(i)
      }
    } else {
      for (let i = start; i <= end; i++) {
        result.push(i)
      }
    }
  })
  return result
}

// 创建多维数组
const _creatMultiArray = (...args) => {
  if (args.length == 1) {
    return new Array(args[0]).fill(0)
  } else {
    return (new Array(args[0]).fill(0)).map((item) => {
      return _creatMultiArray(...args.slice(1))
    })
  }
}




module.exports = {
  getTerm: getTerm,
  getCurrentWeek: getCurrentWeek,
  getCurrentDates: getCurrentDates,
  processFormatForLesson: processFormatForLesson,
  processColorForLessons: processColorForLessons,
  formatClassTable: formatClassTable,
  throttle: throttle
}